import React, {useState, useEffect} from 'react';
import {withRouter} from 'react-router-dom'
import _ from 'lodash';
import AMap from 'AMap';
import {
    ActionSheet,
    NavBar,
    Icon,
    List,
    InputItem,
    TextareaItem,
    Modal,
    SearchBar,
    Checkbox,
    Picker,
    Toast,
    Button,
    DatePicker,
    Accordion,
    Radio,
    Result
} from 'antd-mobile';
import {createForm} from 'rc-form'
import buildSteps from "./common.js";
import {detailsInfo} from "@/api/parent/parent"
import {
    ParentOrderDetails as orderDetails,
    UpdateOrder,
    CommitOrder,
    Delete,
    AddOrderByParent
} from "@/api/order/order.js"
import {getListStudent} from "@/api/parent/chilDinformation.js"
import {R, VOID, ORDER_STATUSES, sexList, subjects, weekList} from "@/assets/js/dict.js"
import './orderDetails.scss';


import nodata from "@/assets/svg/nodata.svg"
import mark from "@/assets/svg/mark.svg"

const myImg = src => <img src={src} className="spe am-icon am-icon-md" alt=""/>;


const confirm = Modal.alert;
const prompt = Modal.prompt;
const CheckboxItem = Checkbox.CheckboxItem;
const RadioItem = Radio.RadioItem;
const Item = List.Item;
const Brief = Item.Brief;

const handlerCache = {
    ov: null
};

/*
* 可编辑的订单详情页，状态只能是“编辑中、已驳回”
* */
function OrderDetailsOfEdit(props) {
    const {getFieldProps} = props.form;
    let [selectTimeVisible, SetSelectTimeVisible] = useState(false); // 时间选择的显隐
    let [selectStudents, SetSelectStudents] = useState(''); // 选中学生
    let [selectStudentsObj, SetSelectStudentsObj] = useState(''); // 选中学生
    let [selectTimeForm, SetSelectTimeForm] = useState({}); // 时间选择的显隐

    let [searchValue, setSearchValue] = useState(""),
        [placeSearch, setPlaceSearch] = useState({});

    let [flush, goFlush] = useState(""),
        [AllStudents, setAllStudents] = useState([]),

        //科目
        [AllSubjects, setAllSubjects] = useState(subjects),
        [order_id] = useState(props.order_id || "2"),
        [isShowSubjectSelector, setIsShowSubjectSelector] = useState(false),
        [isShow, setShow] = useState(false);
    let [status, setStatus] = useState("");
    let [userInfo] = useState(() => {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        return userInfo
    });


    //是否可以编辑，实际上都是可以编辑的，本页面就是编辑用的
    let [editable, enableEdit] = useState("false");
    let [OrderDetailsData, setOrderDetailsData] = useState(() => {
        let def = {students: [], student_ids: "", learn_address: "", learn_hours: "[]"};
        return def;
    });

    // 是否已经存在2个待定订单，不可再继续添加订单 
    let [isShowPage, setIsShowPage] = useState(true);
    let [msg, setMsg] = useState(""); // 盛放新增订单模板的错误信息


    //获取订单详情
    function getOrderDetails() {
        AddOrderByParent({
            parent_id: userInfo.id
        }, (res) => {
            if (R.isSuccess(res)) {
                setIsShowPage(false);
                let data = R.getData(res);
                setStatus(data.status);
                data.learn_hours = data.learn_hours == null ? "[]" : data.learn_hours;
                initMap(data);
                setOrderDetailsData(data);
                enableEdit("true");
                let subs = data.subjects;
                // 学科
                if (!!subs) {
                    setAllSubjects(AllSubjects.map(e => {
                        if (subs.indexOf(e.name) > -1) {
                            e.checked = true;
                        }
                        return e;
                    }));
                }

                //获取家长下的学生，未选中的那些
                getListStudent({parent_id: userInfo.id}).then(res => {
                    if (res[R.code] === R.success) {
                        let ids = data.student_ids;
                        setAllStudents(res[R.data].dataList.map(e => {
                            if (!!ids && ids.indexOf(e.id) > -1) {
                                e.checked = true;
                            }
                            return e;
                        }));
                    } else {
                        Toast.fail(res[R.msg]);
                    }
                }).catch(err => {
                    Toast.fail(err)
                })
            } else {
                setIsShowPage(true);
                setMsg(res[R.msg])
            }
        });


    }

    /**
     * 获取当前位置，并将返回的经纬度作为订单的默认上课地点
     * @param map
     */
    function getCurrentLocal(map) {
        AMap.plugin('AMap.Geolocation', function () {
            let geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000, //超过10秒后停止定位，默认：5s
                showButton: false,
                buttonPosition: 'RB', //定位按钮的停靠位置
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });
            map.addControl(geolocation);
            geolocation.getCurrentPosition(function (status, result) {
                if (status === 'complete') {
                    console.log("getCurrentLocal--->", result);
                    let p = result.position;
                    handlerCache.longitude = p.lng;
                    handlerCache.latitude = p.lat;
                    handlerCache.formattedAddress = result.formattedAddress;
                } else {
                    Toast.fail("GPS定位失败：" + result.messgae, 2, VOID, false)
                }
            });
        });
    }

    function local(mapInstance) {
        console.log("获取当前位置--->");
        AMap.plugin('AMap.Geolocation', function () {
            let geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000, //超过10秒后停止定位，默认：5s
                buttonPosition: 'RB', //定位按钮的停靠位置
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
                showMarker: false

            });
            mapInstance.addControl(geolocation);
            geolocation.getCurrentPosition(function (status, result) {
                if (status === 'complete') {
                    console.log("local--->", result);
                    let p = result.position;
                    handlerCache.longitude = p.lng;
                    handlerCache.latitude = p.lat;
                    handlerCache.formattedAddress = result.formattedAddress;
                    addMarker(mapInstance, handlerCache.ov, p.lng, p.lat);
                } else {
                    Toast.fail("GPS定位失败：" + result.messgae);
                }
            });
        });

    }

    /**
     * 地图的点击响应
     * 点击地图加点标识
     * @param map 地图实例
     * @param ov 覆盖物集合
     * @param e 事件对象
     */
    function showInfoClick(mapInstance, ov, e) {
        let lnglat = e.lnglat;
        getAddress({
            city: "深圳", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
        }, lnglat, (result) => {

            //缓存点击点的经纬
            handlerCache.longitude = lnglat.getLng();
            handlerCache.latitude = lnglat.getLat();
            handlerCache.formattedAddress = result.regeocode.formattedAddress;
            addMarker(mapInstance, ov, lnglat.getLng(), lnglat.getLat());
        });

    }

    // 构建自定义信息窗体
    let createInfoWindow = (title, content, mapInstance) => {
        let info = document.createElement("div");
        info.className = "custom-info input-card content-window-card";

        // 定义顶部标题
        let top = document.createElement("div");
        let titleD = document.createElement("div");
        let closeX = document.createElement("img");
        top.className = "info-top";
        titleD.innerHTML = title;
        closeX.src = "https://webapi.amap.com/images/close2.gif";

        // 关闭信息窗体
        closeX.onclick = () => mapInstance.clearInfoWindow();
        top.appendChild(titleD);
        top.appendChild(closeX);
        info.appendChild(top);

        // 定义中部内容
        let middle = document.createElement("div");
        middle.className = "info-middle";
        middle.style.backgroundColor = '#fff';
        middle.innerHTML = content;
        let copyBtn = document.createElement("button");
        copyBtn.innerHTML = '复制地址';
        copyBtn.style.cssFloat = 'left';
        copyBtn.style.background = '#3d83fa';
        copyBtn.style.color = '#fefefe';
        copyBtn.style.transform = 'translateY(30%)';
        copyBtn.onclick = function () {
            copyAccessKey(middle);
        };
        top.appendChild(copyBtn);
        info.appendChild(middle);

        // 定义底部内容
        let bottom = document.createElement("div");
        bottom.className = "info-bottom";
        bottom.style.position = 'relative';
        bottom.style.top = '0px';
        bottom.style.margin = '0 auto';
        let sharp = document.createElement("img");
        sharp.src = "https://webapi.amap.com/images/sharp.png";
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
    };

    /*
    * 拷贝命令
    * */
    let copyAccessKey = (copyDOM) => {
        let range = document.createRange(); //创建一个range
        window.getSelection().removeAllRanges(); //清楚页面中已有的selection
        range.selectNode(copyDOM); // 选中需要复制的节点
        window.getSelection().addRange(range); // 执行选中元素
        let successful = document.execCommand('copy'); // 执行 copy 操作

        // 移除选中的元素
        window.getSelection().removeAllRanges();
        Toast.success('复制成功!', 1)
    };

    /**
     * 根据经纬度获取详细地址
     * @param geocoderConfig
     * @param lnglat
     * @param call
     */
    function getAddress(geocoderConfig, lnglat, call) {
        let geocoder = new AMap.Geocoder(geocoderConfig);
        geocoder.getAddress(lnglat, (status, result) => {
            if (status === 'complete' && result.regeocode) {
                call(result);
            } else {
                console.error('根据经纬度查询地址失败')
            }
        });
    }

    /**
     * 初始化地址标点，使用数据库中的保存的经纬数据
     * @param mapInstance
     * @param ov
     * @param lng
     * @param lat
     * @param offset
     */
    function initMarker(mapInstance, ov, lng, lat, offset) {
        let markPoint = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),
            offset: offset || new AMap.Pixel(-10, -10),
            icon: mark, // 添加 Icon 图标 URL
            title: '上课地址',
            label: {
                // content: '<span style="color:red; font-size: x-large"><strong>选中的地址</strong></span>'
            }
        });

        //实例化信息窗体
        let lnglat = new AMap.LngLat(lng, lat);
        markPoint.setPosition(lnglat);

        //添加标识物
        mapInstance.add(markPoint);

        //清除之前的标识物
        ov.clearOverlays();

        //保存当前的标识物
        ov.addOverlay(markPoint);

        //查询经纬对应的地址
        let geocoder = new AMap.Geocoder({
            city: "", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
        });
        let address = ''; // 点击坐标的详细地址；
        geocoder.getAddress(lnglat, (status, result) => {
            if (status === 'complete' && result.regeocode) {
                address = result.regeocode.formattedAddress;
                handlerCache.formattedAddress = address;

                //实例化信息窗体
                let title = '详细地址：',
                    content = [];
                content.push(address);

                //构建自定义信息窗体
                let infoWindow = new AMap.InfoWindow({
                    position: new AMap.LngLat(lnglat.getLng(), lnglat.getLat()),
                    offset: new AMap.Pixel(24, -4),
                    autoMove: true,
                    isCustom: true, //使用自定义窗体
                    content: createInfoWindow(title, content.join("<br/>"), mapInstance),
                });

                infoWindow.open(mapInstance);

                //鼠标点击marker弹出自定义的信息窗体
                AMap.event.addListener(markPoint, 'click', function () {
                    infoWindow.open(mapInstance, markPoint.getPosition());
                });
            } else {
                console.error('根据经纬度查询地址失败', result, status)
            }
        });
    }

    /**
     * 地址点击事件及搜索事件，添加标识物
     * @param map 地图实例
     * @param ov 覆盖物组
     * @param lng 经度
     * @param lat 纬度
     */
    function addMarker(mapInstance, ov, lng, lat, offset) {
        let markPoint = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),
            offset: offset || new AMap.Pixel(-10, -10),
            icon: mark, // 添加 Icon 图标 URL
            title: '上课地址'
        });

        //实例化信息窗体
        let title = '详细地址：', content = [];
        content.push(handlerCache.formattedAddress);

        //构建自定义信息窗体
        let infoWindow = new AMap.InfoWindow({
            position: new AMap.LngLat(lng, lat),
            offset: new AMap.Pixel(24, -4),
            autoMove: true,
            isCustom: true, //使用自定义窗体
            content: createInfoWindow(title, content.join("<br/>"), mapInstance),
        });

        infoWindow.open(mapInstance);

        //添加标识物
        mapInstance.add(markPoint);

        //鼠标点击marker弹出自定义的信息窗体
        AMap.event.addListener(markPoint, 'click', function () {
            infoWindow.open(mapInstance, markPoint.getPosition());
        });

        //清除之前的标识物
        ov.clearOverlays();

        //保存当前的标识物
        ov.addOverlay(markPoint);

        //设置点击起点的经纬
        handlerCache.longitude = lng;
        handlerCache.latitude = lat;
    }

    useEffect(() => {
        getOrderDetails(); // 订单模板
    }, [flush]);

    /*
    * 初始化地图
    * */
    function initMap(obj) {
        let auto;
        //输入提示
        AMap.plugin(['AMap.Geocoder', 'AMap.Marker', 'AMap.LngLat', 'AMap.Pixel', 'AMap.Icon', 'AMap.OverlayGroup', 'AMap.Autocomplete'], () => {
            auto = new AMap.Autocomplete({
                input: document.querySelector(".am-search-value")
            });
        });
        let mapInstance;
        if (obj && null !== obj.longitude && null !== obj.latitude) {
            let pp = [obj.longitude, obj.latitude];
            mapInstance = new AMap.Map('amap', {
                resizeEnable: true,
                zoomEnable: true,
                dragEnable: true,
                center: pp,//传入地址的经纬度
                zoom: 13
            });
            mapInstance.on('complete', function () {
                handlerCache.mapObj = mapInstance;
                initSearch(mapInstance, auto);
            });
            let ov = new AMap.OverlayGroup([]);
            handlerCache.ov = ov;
            ov.setMap(mapInstance);
            mapInstance.on("click", (e) => showInfoClick(mapInstance, ov, e));
            initMarker(mapInstance, ov, obj.longitude, obj.latitude);
        } else {

            // 创建地图实例
            mapInstance = new AMap.Map('amap', {
                resizeEnable: true,
                zoomEnable: true,
                dragEnable: true,
                zoom: 13
            });
            mapInstance.on('complete', function () {
                handlerCache.mapObj = mapInstance;
                getCurrentLocal(mapInstance);
                initSearch(mapInstance, auto);
            });

            let ov = new AMap.OverlayGroup([]);
            ov.setMap(mapInstance);
            handlerCache.ov = ov;
            mapInstance.on("click", (e) => showInfoClick(mapInstance, ov, e));

        }
    }

    function initSearch(map, auto) {

        //输入提示
        AMap.plugin(['AMap.PlaceSearch'], () => {
            let placeSearch = new AMap.PlaceSearch({
                map: map
            }); //构造地点查询类
            handlerCache.placeSearch = placeSearch;
            setPlaceSearch(placeSearch);
            auto.on("select", (e) => {
                placeSearch.setCity(e.poi.adcode);
                setSearchValue(e.poi.name);
                placeSearch.search(e.poi.name); //关键字查询查询
            });//注册监听，当选中某条记录时会触发

            /**
             * 搜索结果覆盖物点击事件
             */
            placeSearch.on("markerClick", (e) => {
                let data = e.data;
                console.log("placeSearch.click----> ", e, placeSearch.render, handlerCache);
                let lnglat = new AMap.LngLat(data.location.lng, data.location.lat);
                getAddress({}, lnglat, (result) => {
                    handlerCache.formattedAddress = result.regeocode.formattedAddress;
                    addMarker(map, handlerCache.ov, data.location.lng, data.location.lat, new AMap.Pixel(-20, -34));
                });
            });
        });
    }


    /**
     * 提交订单审核，需要检测是否已经是vip
     * 还应该对订单字段进行验证、学生数量大于0
     */
    function commitOrder() {
        confirm('提交订单', '确定要提交订单吗', [
            {
                text: '取消', onPress: () => {}
            },
            {
                text: '确定', onPress: () => { //1 检测是否是会员
                    detailsInfo({parent_id: userInfo.id}, (res) => {
                        if (res[R.code] === R.success) {
                            let data = res[R.data];
                            let info = {
                                username: data.name,
                                id: data.id,
                                type: data.role,
                                is_vip: data.is_vip,
                                vip_limit: data.vip_limit
                            };
                            console.log("detailsInfo-->", info);
                            sessionStorage.setItem("userInfo", JSON.stringify(info));
                            if (!info.is_vip) {
                                confirm('提示', '您还不是会员，暂不具备招聘家教资格，成为会员才能提交订单', [
                                    {text: '取消', onPress: () => console.log('cancel')},
                                    {
                                        text: '确定', onPress: () => {
                                            props.history.push("/payOfVip");
                                        }
                                    },
                                ]);
                            } else {
                                //2 检查必填的项
                                let formObj = props.form.getFieldsValue().OrderDetailsData;
                                let isBlank = /^\s*$/;
                                console.log("formObj---> ", formObj);
                                for (let f in formObj) {
                                    if (formObj[f] === undefined || formObj[f] === null || isBlank.test(formObj[f])) {
                                        console.log("f----> ", f);
                                        if (f == 'student_ids') {
                                            Toast.info("学生列表为空", 2, VOID, false);
                                        } else {
                                            Toast.info("检测到有未填的项，请完善订单信息再提交", 2, VOID, false);

                                        }
                                        return
                                    }
                                }
                                silentSave(() => {
                                    CommitOrder({order_id: OrderDetailsData.id}, res => {
                                        if (res[R.code] === R.success) {
                                            Toast.success("订单提交成功，等待平台审核", 2, VOID, false);

                                            //跳转到找家教页面
                                            props.history.push("/lookForTutor");
                                        } else {
                                            Toast.fail(res[R.msg]);
                                        }
                                    });
                                });
                            }
                        }
                    });
                }
            },
        ]);
    }


    /**
     * 删除订单
     */
    function deleteOrder(reason) {
        Delete({order_id: OrderDetailsData.id, reason: reason}).then(res => {
            if (res[R.code] === R.success) {
                Toast.success("订单提交成功，等待平台审核")
            } else {
                Toast.fail(res[R.msg]);
            }
        }).catch(err => Toast.fail(err));
    }


    //待选的学生
    // const studentsSelector = function () {
    //     console.log("AllStudents---> ", AllStudents);
    //     return (

    //     );
    // };


    // const subjectsSelector = function () {
    //     return (

    //     );
    // };

    /**
     * 选择科目
     * @param e
     * @param index
     * @param obj
     */
    function checkSubject(e, index, obj) {
        if (e.target.checked) {
            obj.checked = true;
            setAllSubjects([...AllSubjects]);
        } else {
            obj.checked = false;
            setAllSubjects([...AllSubjects]);
        }
    }

    /**
     * 完成科目选择
     */
    function finishSubjectCheck() {
        let subs = null, count = 0;
        AllSubjects.forEach((e, i) => {
            if (e.checked) {
                if (subs == null) {
                    subs = e.name;
                } else {
                    subs = subs + "," + e.name;
                }
            }
        });
        OrderDetailsData.subjects = subs;
        if (OrderDetailsData.subjects.indexOf('其他') != -1) {
            OrderDetailsData.class_fee = '价格标准请联系客服人员确定'
        }
        console.log("finishSubjectCheck------> ", OrderDetailsData);
        setOrderDetailsData(_.cloneDeep(OrderDetailsData));
        setIsShowSubjectSelector(false);
    }

    //恢复科目选择器
    function recoverSubjectSelector() {
        let subs = OrderDetailsData.subjects;
        if (subs) {
            AllSubjects.forEach(item => {
                item.checked = subs.indexOf(item.id) > -1;
            });
            setAllSubjects(AllSubjects);
        }
    }

    /**
     * 选中一个学生
     * @param obj
     */
    function checkStudent(e, index, obj) {
        SetSelectStudents(obj.id);
        SetSelectStudentsObj(obj)
    }


    /**
     * 只更新订单的学生部分内容
     * @param ids 学生id，以逗号分隔
     */
    // function saveStudentsOnly (ids) {

    //     /*暂存页面的内容*/
    //     let newData = buildFormData();
    //     _.merge(OrderDetailsData, newData);
    //     OrderDetailsData.student_ids = ids;
    //     let params = { id: OrderDetailsData.id, student_ids: ids };
    //     UpdateOrder(params).then(res => {
    //         Toast.hide();
    //         if (res[R.code] === R.success) {
    //             let obj = res[R.data], students = obj.students;
    //             OrderDetailsData.students = students;
    //             OrderDetailsData.class_fee = obj.class_fee;
    //             setOrderDetailsData(_.cloneDeep(OrderDetailsData));
    //             recoverStudentSelector();
    //         } else {
    //             Toast.fail(res[R.msg]);
    //         }
    //     }).catch(err => {
    //         Toast.fail(err)
    //     })
    // }


    /**
     * 选择学生的
     */
    function trySaveStudents() {
        // 更新详情数据中学生列表
        console.log('selectStudents ------>>>', selectStudents);
        let newOrderDetailsData = {...OrderDetailsData};
        newOrderDetailsData.students.length = 0;
        newOrderDetailsData.students.push(selectStudentsObj); // 选中的学生信息 
        newOrderDetailsData.student_ids = selectStudents;// 选中的学生信息 ID

        if (selectStudentsObj.grade.indexOf('其他') != -1) {
            newOrderDetailsData.class_fee = '价格标准请联系客服人员确定'
        }

        console.log('newOrderDetailsData ------>', newOrderDetailsData);

        setOrderDetailsData(newOrderDetailsData);

        setShow(false); // 关闭弹框  
    }

    /**
     * 恢复学生待选状态
     */
    function recoverStudentSelector() {
        let newOrderDetailsData = {...OrderDetailsData};
        if (OrderDetailsData.students.length) {
            if (selectStudentsObj.id == newOrderDetailsData.students[0].id) {
                newOrderDetailsData.students.splice(0, 1)
            }
        }

    }

    /*
    * 保存订单数据
    * */
    function saveOrderInfo() {
        let data = buildFormData();
        Toast.loading("保存数据...", 3, () => {
        }, true);

        UpdateOrder(data).then(res => {
            Toast.hide();
            if (res[R.code] === R.success) {
                goFlush(new Date().getTime());
                Toast.success("保存成功", 2, VOID, false);
            } else {
                Toast.fail("保存数据异常：" + res[R.msg]);
            }
        }).catch(err => {
            Toast.fail(err)
        })
    }

    /**
     * 拼接学生id
     * @returns {*}
     */
    function concatStudentIds() {
        //提取选中的学生
        let ids = null;
        AllStudents.forEach((e, i) => {
            if (e.checked) {
                if (ids == null) {
                    ids = e.id;
                } else {
                    ids = ids + "," + e.id;
                }
            }
        });
        return ids;
    }

    /**
     * 构建将要提交的表单数据
     * @returns {*}
     */
    function buildFormData() {
        let formObj = props.form.getFieldsValue().OrderDetailsData,
            order = _.cloneDeep(OrderDetailsData);

        /*
        * 合并表单的数据
        * */
        _.merge(order, formObj);
        order.student_ids = selectStudents;
        if (!!handlerCache.longitude) {
            order.longitude = handlerCache.longitude;
        }
        if (!!handlerCache.latitude) {
            order.latitude = handlerCache.latitude;
        }

        if (!!order.parent_gender) {
            order.parent_gender = order.parent_gender[0];
        }
        return order;
    }


    /*
    * 保存订单数据
    * */
    function silentSave(call) {
        let data = buildFormData();
        console.log('data ---->>', data);

        UpdateOrder(data).then(res => {
            Toast.hide();
            if (res[R.code] === R.success) {
                call();
            } else {
                Toast.fail("保存数据异常：" + res[R.msg]);
            }
        }).catch(err => {
            Toast.fail(err)
        })
    }

    //渲染订单中的学生
    function renderStudents() {
        if (OrderDetailsData.students.length) {
            return (OrderDetailsData.students.map((item, index) => {
                return (
                    <Item key={index}
                          arrow="empty"
                          multipleLine
                          onClick={() => {
                              console.log("item-->", item);
                          }}
                          platform="cross"
                    >
                        名称：{item.name}
                        <Brief> 年龄：{item.age}</Brief>
                        <Brief> 年级：{item.grade}</Brief>
                        <Brief> 说明：{item.note}</Brief>
                    </Item>
                )
            }));
        } else {
            return (<Item/>)
        }
    }

    function rejectReason() {
        if (status === ORDER_STATUSES.REJECTED) {
            return (
                <div className="form-con">
                    <List>
                        <TextareaItem
                            rows="3"
                            autoHeight
                            rows={5}
                            value={OrderDetailsData.publish_audit_comment}
                        />
                    </List>
                </div>
            )
        } else {

        }

    }

    function back() {
        props.history.goBack();

    }


    // 上课时间删除
    function handleDelLearnHours(val) {
        let newOrderDetailsData = {...OrderDetailsData};

        Modal.alert('提示', '您确定要删除改时间段吗？', [
            {text: '取消', onPress: () => console.log('cancel'), style: 'default'},
            {
                text: '确定', onPress: () => {
                    let learnHoursArr = JSON.parse(OrderDetailsData.learn_hours);
                    learnHoursArr.map((i, index) => {
                        if (val.week === i.week) {
                            learnHoursArr.splice(index, 1)
                        }
                    });
                    newOrderDetailsData.learn_hours = JSON.stringify([...learnHoursArr]);
                    setOrderDetailsData(newOrderDetailsData)

                }
            },
        ]);

        console.log('OrderDetailsData ------->>>', OrderDetailsData)
    }


    if (isShowPage) {
        return (
            <div className="orderDetails">
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left"/>}
                        leftContent={<span key="rc"/>}
                        onLeftClick={back}
                    >
                        {status === ORDER_STATUSES.EDITING ? '制作中的订单' : ''}
                    </NavBar>
                </div>


                <div className="page-content  home-content">
                    <div className="publish-content-piece">
                        <Result
                            buttonText={"返回上一页"}
                            img={myImg(nodata)}
                            title=""
                            message={msg}
                            buttonType="primary"
                            onButtonClick={() => {
                                props.history.goBack()
                            }}
                        />
                    </div>
                </div>


            </div>
        )
    } else {
        return (
            <div className="orderDetails">
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left"/>}
                        leftContent={<span key="rc"/>}
                        // rightContent={[
                        //     <span key="1" onClick={showActionSheet}>操作</span>
                        // ]}
                        onLeftClick={back}
                    >
                        {status === ORDER_STATUSES.EDITING ? '制作中的订单' : ''}
                    </NavBar>
                </div>

                <div className="page-content  home-content">
                    <div className="publish-content-piece">


                        <div className="form-box">
                            <div className="form-con">
                                {buildSteps(status)}
                            </div>
                            <div className="form-tit"
                                 style={{display: (status === ORDER_STATUSES.REJECTED ? 'block' : 'none')}}
                            >
                                <i className="mini-block"/>
                                <strong>
                                    驳回说明
                                </strong>
                            </div>
                            {rejectReason(OrderDetailsData)}
                            <div className="form-tit">
                                <i className="mini-block"/>
                                <strong>
                                    基本信息
                                </strong>
                            </div>
                            <div className="form-con">

                                <List>
                                    <InputItem
                                        type="text"
                                        editable={editable}
                                        {...getFieldProps('OrderDetailsData.parent_name', {initialValue: OrderDetailsData.parent_name})}
                                    >家长姓名</InputItem>

                                    <Picker data={sexList}
                                            cols={1} {...getFieldProps('OrderDetailsData.parent_gender', {initialValue: [OrderDetailsData.parent_gender]})}
                                    >
                                        <List.Item arrow="horizontal" editable={editable}>家长性別</List.Item>
                                    </Picker>
                                    <div onClick={() => setIsShowSubjectSelector(true)}>
                                        <InputItem
                                            editable="false"
                                            placeholder="请选择辅导科目"
                                            {...getFieldProps('OrderDetailsData.subjects', {initialValue: OrderDetailsData.subjects})}
                                        >
                                            辅导科目
                                        </InputItem>
                                    </div>
                                    <InputItem
                                        editable={false}
                                        placeholder="课时费在选择时自动计算"
                                        value={OrderDetailsData.class_fee ? (isNaN(OrderDetailsData.class_fee) && OrderDetailsData.class_fee !== 0 ? OrderDetailsData.class_fee : "￥" + OrderDetailsData.class_fee / 100) : ''}
                                    >课时费</InputItem>
                                </List>
                            </div>
                            <div className="form-tit">
                                <i className="mini-block"/>
                                <strong>
                                    可授课时间段
                                </strong>
                            </div>
                            <div className="form-con">
                                <Accordion defaultActiveKey="0" className="my-accordion">
                                    {
                                        JSON.parse(OrderDetailsData.learn_hours) ?
                                            JSON.parse(OrderDetailsData.learn_hours).map((item, index) => {
                                                return <Accordion.Panel header={
                                                    <div>
                                                        {item.week}
                                                        <span className="time-del" onClick={() => {
                                                            handleDelLearnHours(item)
                                                        }}
                                                        >
                                                            删除
                                                    </span>
                                                    </div>
                                                } key={index}
                                                >
                                                    <List className="my-list">
                                                        <Item extra={item.startTime}>开始日期</Item>
                                                        <Item extra={item.endTime}>结束日期</Item>
                                                    </List>
                                                </Accordion.Panel>
                                            })
                                            :
                                            ''
                                    }
                                </Accordion>

                                <Button type="primary" onClick={() => {
                                    SetSelectTimeVisible(true)
                                }}
                                >添加时间</Button>
                            </div>
                            <div className="form-tit">
                                <i className="mini-block"/>
                                <strong>
                                    上课地址（具体到小区）
                                </strong>
                            </div>
                            <div className="form-con">
                                <List>
                                    <TextareaItem
                                        editable={editable}
                                        clear
                                        rows="3"
                                        placeholder="请手动输入，或根据下方地图的“定位当前位置”复制地址”"
                                        autoHeight
                                        id={"555"}
                                        {...getFieldProps('OrderDetailsData.learn_address', {initialValue: OrderDetailsData.learn_address})}
                                    />
                                </List>
                                <SearchBar
                                    placeholder="查找地址"
                                    value={searchValue}
                                    onSubmit={value => {
                                        placeSearch.search(value);
                                        let target = document.querySelector(".amap-sug-result");
                                        target.style.display = 'none';
                                    }}
                                    onClear={value => setSearchValue("")}
                                    onCancel={() => {
                                        local(handlerCache.mapObj);
                                    }}
                                    showCancelButton
                                    cancelText="定位当前位置"
                                    onChange={setSearchValue}
                                />
                                <div id="amap" style={{width: '100%', height: '300px'}}/>
                            </div>
                            <div className="form-tit">
                                <i className="mini-block"/>
                                <strong>学生</strong>
                            </div>
                            <div className="form-con">
                                <Button style={{marginBottom: '20px'}} type="primary" onClick={() => {
                                    setShow(true);
                                }}
                                >选择学生</Button>
                                <List>
                                    {renderStudents()}
                                </List>
                            </div>
                            <div className="form-tit">
                                <i className="mini-block"/>
                                <strong>对家教老师的要求</strong>
                            </div>
                            <div className="form-con">
                                <List>
                                    <TextareaItem
                                        editable={editable}
                                        clear
                                        rows="6"
                                        autoHeight
                                        placeholder="请输入对家教老师的要求，内容为200字以内"
                                        count={200}
                                        {...getFieldProps('OrderDetailsData.demand', {initialValue: OrderDetailsData.demand})}
                                    />
                                </List>
                            </div>


                            <Button type="ghost" size="small"
                                    style={{fontSize: '18px', margin: '16px 0px ', height: '47px', lineHeight: '47px'}}
                                    onClick={saveOrderInfo}
                            >保存订单</Button>

                            <Button type="primary" onClick={commitOrder}
                            >提交订单</Button>
                        </div>
                    </div>
                </div>

                {/* 选择学生 */}
                <Modal
                    visible={isShow}
                    transparent
                    maskClosable
                    title="选择学生"
                    onClose={() => setShow(false)}
                    footer={[{
                        text: '取消', onPress: () => setShow(false)
                    }, {
                        text: '确定', onPress: trySaveStudents
                    }]}
                    afterClose={() => setShow(false)}
                >
                    <div style={{height: 200, overflow: 'scroll'}}>
                        <List>{
                            AllStudents.map((item, index) => (
                                <RadioItem key={item.id} checked={selectStudents === item.id}
                                           onChange={(e) => checkStudent(e, index, item)}
                                >
                                    {item.name}-{item.grade}
                                </RadioItem>
                            ))
                        }</List>
                    </div>
                </Modal>

                {/* 选择科目 */}
                <Modal
                    visible={isShowSubjectSelector}
                    transparent
                    maskClosable
                    title="科目选择"
                    footer={[{
                        text: '取消', onPress: () => {
                            setIsShowSubjectSelector(false);
                        }
                    }, {
                        text: '确定', onPress: () => {
                            finishSubjectCheck();
                        }
                    }]}
                    afterClose={recoverSubjectSelector}
                >
                    <div style={{height: 200, overflow: 'scroll'}}>
                        <List>{
                            AllSubjects.map((item, index) => (
                                <CheckboxItem key={index} checked={item.checked}
                                              onChange={(e) => checkSubject(e, index, item)}
                                >
                                    {item.name}
                                </CheckboxItem>
                            ))
                        }</List>
                    </div>
                </Modal>

                {/* 时间选择 */}
                <Modal
                    visible={selectTimeVisible}
                    transparent
                    maskClosable
                    animationType="slide-up"
                    title="时间选择"
                    footer={[{
                        text: '取消', onPress: () => {
                            SetSelectTimeVisible(false)
                        }
                    }, {
                        text: '确定', onPress: () => {

                            // 时间选择
                            let timeData = props.form.getFieldsValue().selectTimeForm,
                                learnHoursNew = JSON.parse(OrderDetailsData.learn_hours); // 数据类型  订单详情中已有的时间

                            if (timeData.week && new Date(timeData.startTime).getHours() && new Date(timeData.endTime).getHours()) {
                                timeData.week = timeData.week ? timeData.week[0] : '';
                                // 判断开始时间为空
                                if (new Date(timeData.startTime).getHours()) {
                                    timeData.startTime = new Date(timeData.startTime).getHours() + '点' + new Date(timeData.startTime).getMinutes() + '分'
                                }

                                // 判断结束时间为空 
                                if (new Date(timeData.endTime).getHours()) {
                                    timeData.endTime = new Date(timeData.endTime).getHours() + '点' + new Date(timeData.endTime).getMinutes() + '分'
                                }

                                let newOrderDetailsData = OrderDetailsData;
                                learnHoursNew.push(timeData);
                                newOrderDetailsData.learn_hours = JSON.stringify([...learnHoursNew]);

                                setOrderDetailsData(newOrderDetailsData);
                                SetSelectTimeVisible(false)
                            } else {
                                Toast.fail('内容不能为空', 1);

                            }

                        }
                    }]}
                    afterClose={() => {
                        SetSelectTimeVisible(false)
                    }}
                >
                    <div>
                        <List>
                            <Picker data={weekList} cols={1}
                                    value={selectTimeForm.week}
                                    format={(labels) => {
                                        return labels.join(',')
                                    }}
                                    onChange={(val) => {
                                        let newSelectTimeForm = selectTimeForm;
                                        newSelectTimeForm.week = val;
                                        console.log(newSelectTimeForm);

                                        SetSelectTimeForm(newSelectTimeForm)
                                    }}
                                    {...getFieldProps('selectTimeForm.week')}
                            >
                                <List.Item arrow="horizontal">周</List.Item>
                            </Picker>
                            <DatePicker
                                mode="time"
                                onChange={(val) => {
                                    let newSelectTimeForm = selectTimeForm;
                                    newSelectTimeForm.startTime = val;
                                    console.log(newSelectTimeForm);

                                    SetSelectTimeForm(newSelectTimeForm)
                                }}
                                {...getFieldProps('selectTimeForm.startTime')}
                            >
                                <List.Item arrow="horizontal">开始时间</List.Item>
                            </DatePicker>
                            <DatePicker
                                mode="time"
                                onChange={(val) => {
                                    let newSelectTimeForm = selectTimeForm;
                                    newSelectTimeForm.endTime = val;
                                    console.log(newSelectTimeForm);
                                    SetSelectTimeForm(newSelectTimeForm)
                                }}
                                {...getFieldProps('selectTimeForm.endTime')}
                            >
                                <List.Item arrow="horizontal">结束时间</List.Item>
                            </DatePicker>
                        </List>
                    </div>
                </Modal>
            </div>
        );

    }

}

OrderDetailsOfEdit = createForm()(OrderDetailsOfEdit);
export default withRouter(OrderDetailsOfEdit);